<?php

namespace app\common\model;

use think\Cache;
use think\Db;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\exception\DbException;
use think\Model;

/**
 * 题库
 */
class Question extends Model
{

    // 表名
    protected $name = 'question';

    /**
     * 题库列表
     * @param mixed $question_group_id 
     * @param int $user_id 
     * @return mixed 
     * @throws DbException 
     */
    public function getFixListByPaper($question_group_id, $user_id = 0)
    {
        $questions = self::alias('question_model')
            ->join('question_paper qp', 'question_model.id = qp.question_id')
            ->where('qp.question_group_id', $question_group_id)
            ->where('question_model.deletetime IS NULL')
            ->where('question_model.status', 'NORMAL')
            ->field('question_model.id as question_id,question_model.kind,question_model.title,question_model.explain,question_model.difficulty,question_model.options_json,question_model.options_img,question_model.status,qp.answer_config as answer,qp.question_group_id')
            ->order('question_model.weigh', 'asc')
            ->paginate();
        $questionUserAnswers = [];
        if ($user_id > 0) {
            # 查询用户答题信息
            $questionUserAnswers = (new UserAnswers())->getListUserAnswers($user_id);
        }
        $questions = getQuestionArray($questions, $questionUserAnswers, true);
        return $questions;
    }



    /**
     * 智能推荐
     * @param mixed $mock_id 
     */
    public function getQuestionRandom($mock_id, $question_count)
    {
        $list = self::where(function ($query) use ($mock_id) {
            if ($mock_id > 0) {
                $query->where('mock_id', $mock_id);
            }
            $query->where('deletetime IS NULL');
            $query->where('status', 'NORMAL');
        })
            ->field('id as question_id,kind,title,explain,difficulty,options_json,options_img,answer,status')
            ->orderRaw('RAND()')
            ->paginate($question_count);
        return getQuestionArray($list);
    }


    /**
     * 提卡信息
     * @param mixed $user_id 
     * @param mixed $question_group_id 
     */
    public function getCardQuestion($user_id, $question_group_id)
    {
        # 查询用户答题
        $userAnswers = UserAnswers::where(['user_id' => $user_id, 'question_group_id' => $question_group_id])->column('is_right', 'question_id');
        # 正确题
        $correct = count(array_filter($userAnswers, fn($v) => (int)$v === 1 || (int)$v === 3));
        # 错误题
        $wrong = count(array_filter($userAnswers, fn($v) => (int)$v === 0));
        # 查询刷题组卷题目id
        $list = self::alias('question_model')
            ->join('question_paper qp', 'question_model.id = qp.question_id')
            ->where('qp.question_group_id', $question_group_id)
            ->where('question_model.deletetime IS NULL')
            ->where('question_model.status', 'NORMAL')
            ->field('question_model.id as question_id,qp.answer_config as answer,qp.question_group_id')
            ->order('question_model.weigh', 'asc')
            ->paginate(50)->each(function ($item) use (&$userAnswers) {
                $item['is_right'] = $userAnswers[$item['question_id']] ?? '-1';  # 1和3都是正确，0错误，-1未答
                return $item;
            });
        return $list; # 题库列表
    }


    /**
     * 查看我的错误  预览我的错题
     * @param array $extend 
     * @param array $questionUserAnswers 
     * @param bool $recordUser 
     * @return mixed 
     */
    public function getListQuestion($extend = [], $questionUserAnswers = [], $recordUser = true)
    {
        $where = [];
        if (isset($extend['id']) && $extend['id']) {
            $where['id'] = ['in', $extend['id']];
        }
        $list = self::where($where)
            ->field('id as question_id,kind,title,explain,difficulty,options_json,options_img,answer,status')
            ->order(['weigh' => 'asc'])
            ->select();
        return getQuestionArray($list, $questionUserAnswers, $recordUser);
    }



    /***-------------------------------考试-------------------------------------------- */
    
    /**
     * 考试题目数据
     * @param mixed $exam_paper_id 
     * @param int $user_id 
     */
    public function getFixListByExamPaper($exam_paper_id, $user_id = 0)
    {
        if(!$exam_paper_id) fail("试卷id错误");
        $questions = self::alias('question_model')
            ->join('exam_paper_question pq', 'question_model.id = pq.question_id')
            ->where('pq.paper_id', $exam_paper_id)
            ->field('question_model.id as question_id,question_model.kind,question_model.title,question_model.explain,question_model.difficulty,question_model.options_json,question_model.options_img,question_model.status, pq.score,pq.answer_config as answer')
            ->order('question_model.weigh', 'asc')
            ->select();
        return getQuestionArray($questions);
    }



    /**
     * 查询考试解析
     * @param mixed $question_ids 
     * @return array 
     */
    public function getUserAnalysisQuestions($question_ids){
        $list = self::whereIn('id', $question_ids)->field('id as question_id,kind,title,explain,difficulty,options_json,options_img,answer,status,explain')->select();
        $list = getQuestionArray($list, [], false);
        return collection((array)$list)->toArray();
    }

}
